package com.yz.xyt.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传工具类
 * @author JW.WANG
 */
public class FileUploadUtils {

    /**
     * 文件上传
     * @param multipartFile 上传的文件
     * @param baseDir 上传根路径
     * @return 文件存储的路径
     * @throws IOException
     */
    public static final String upload (MultipartFile multipartFile,String baseDir)throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();

        String fileName = extractFilename(originalFilename);

        File dest = getAbsoluteFile(baseDir,fileName);
        multipartFile.transferTo(dest);
        return dest.getPath();
    }

    /**
     * 编码存储的文件名
     * @param originalFilename
     * @return
     */
    public static final String extractFilename(String originalFilename){
        String extension = FilenameUtils.getExtension(originalFilename);
        String fileName = DateUtils.datePath() +  "/" + UUIDUtils.simpleUUID() + "." + extension;
        return fileName;
    }


    public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.exists())
        {
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }
}
